#include "led_task.h"
#include "key_task.h"
#include <stdio.h>
#include "main.h"
#include "cmsis_os.h"
#include "tim.h"
#include "elog.h"


uint8_t LED_blink_counter = 0;

static void led_task(void);
static void led_on(void);
static void led_off(void);
static void led_toggle(void);



led_interface_t led_interface = {
    .pftask = led_task,
    .pfled_on = led_on,
    .pfled_off = led_off,
    .pfled_toggle = led_toggle
};

static void led_on(void)
{
    HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_RESET);
}

static void led_off(void)
{
    HAL_GPIO_WritePin(LED_GPIO_Port, LED_Pin, GPIO_PIN_SET);
}

static void led_toggle(void)
{
    HAL_GPIO_TogglePin(LED_GPIO_Port, LED_Pin);
}


static void led_task(void)
{
    key_result_t *result;
    result = key_interface.pfget_result();
    switch (*result)
    {
        case KEY_SHORT_PRESS:
            LED_blink_counter += 2;
            break;
        case KEY_LONG_PRESS:
            LED_blink_counter += 20;
            break;
        default:
            break;
    }
    if (0 < LED_blink_counter)
    {
        __HAL_TIM_SetCounter(&htim3, 0);
        HAL_TIM_Base_Start_IT(&htim3);
    }

    log_i("current tick: %d", HAL_GetTick());
}

void TIM3_callback(void)
{
    if (--LED_blink_counter == 0)
    {
        HAL_TIM_Base_Stop_IT(&htim3);
    }

    led_interface.pfled_toggle();
}